package client;

import java.applet.Applet;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client extends Thread{
	
	private Socket socket;
	private DataInputStream din;
	private DataOutputStream dout;
	private String host = "137.48.181.131";
	private int port = 4444;
	private Lot lot;
	private ClientGUI gui;
	
	public Client(String host, Lot lot, ClientGUI gui){
		this.host = host;
		this.lot = lot;
		this.gui = gui;		
	}

		public boolean connect(){
		try {
			// Initiate the connection
			socket = new Socket( host, port );
			//Log the connection established
			//logNotif("Connection to " + socket + " Successful!", "ALERT");
			//create DataInput/Output streams from socket streams
			din = new DataInputStream( socket.getInputStream() );
			dout = new DataOutputStream( socket.getOutputStream() );
			//showStatus("This worked!");
			//gui.setConnectStatus(true);
			// Start a background thread for receiving messages
			new Thread( this ).start();
			return true;
		} catch( IOException ie ) { 
			System.out.println( ie );
			return false;
			}
	}
		
		public void run() {
			try {
				// Receive messages one-by-one, forever
				while (true) {
					// Get the next message

					String message = din.readUTF();
					String [] temp = new String[3];
					if ( message.startsWith("[")){
						temp = parseMessage(message);
						lot.setLotID(Integer.parseInt(temp[0]));
						lot.setLotCount(Integer.parseInt(temp[1]));
						lot.setLotSize(Integer.parseInt(temp[2]));
						gui.refresh();
					}
					
				}
			} catch( IOException ie ) { System.out.println( ie ); }
		}

		private String[] parseMessage(String message) {
			String [] temp = new String[3];
			message = message.replaceAll("\\[", ""); 
			message = message.replaceAll("\\]", ""); //removes the brackets
			temp = message.split(":", 3);
			return temp;
			
			
			
		}

		public void sendMessage(String message) throws IOException {
			dout.writeUTF(message);
			
		}

}
